#ifndef _TASK_H_
#define _TASK_H_

#include <list>
#include <core/common_types.h>
#include <core/comdefs.h>
#include <core/system/simple_timer.h>

#ifdef WIN32
#include <memory>
#pragma comment(lib,"ws2_32.lib")
#endif

namespace qb
{
	class CTask;
	class ITaskObserver
	{
	public:
		virtual void OnTaskStep(qb::NetStatus status, short ret_code) = 0;
		virtual void OnTaskFinished(CTask* pTask) = 0;
		virtual void OnTaskFailed(CTask* pTask, qb::NetStatus status, short nRetCode) = 0;
	};

    class CTask
    {
    public:
        CTask();
        virtual ~CTask();

        bool IsRunning() const;
        bool IsFinished() const;
        bool IsFailed() const;

        void SetObserver(ITaskObserver* pObserver);

        void Start();
        void Terminate(bool bForce = false);
        void OnRecvNetData(char* pRecvData, int nDataLen);
		void OnRecvNetStatus(int status);
        virtual bool IsConnectTask() = 0;

	protected:
		virtual void StartImpl() = 0;
		virtual void TerminateImpl() = 0;
		virtual void OnNetData(char* pData, int nDataLen) = 0;
		virtual void OnNetStatus(int status) = 0;
        virtual int32_t GetTaskTimeout() = 0;

    protected:
        void NotifyFinished();
        void NotifyFailed(qb::NetStatus uStep, short nRetCode);

	protected:
        void StartTaskTimer();
        void StopTaskTimer();
		void NotifyLoginStep(qb::NetStatus uStep, short nRetCode);
        virtual void OnTimeout();

	private:
		// 超时回调函数
		static void TimerCallback(int32_t nTimerID, void* pUserData);

    protected:
        enum Status
        {
            eNone,
            eRunning,
            eFinished,
            eFailed
        };

        Status							m_eStatus;		// 状态
        ITaskObserver*					m_pObserver;

        simple_timer                    m_timer;
    };
}

#endif
